package com.ycsj.goldmedalnewconcept.teacher.activity;

import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.ycsj.common.base.BaseActivity;
import com.ycsj.common.base.BaseApplication;
import com.ycsj.common.base.BusInfo;
import com.ycsj.common.manager.BqaManager;
import com.ycsj.common.manager.CustomDialogManager;
import com.ycsj.common.manager.PopUpManager;
import com.ycsj.common.manager.SrfManager;
import com.ycsj.common.utils.GsonUtil;
import com.ycsj.common.utils.StateBarUtil;
import com.ycsj.common.utils.UiUtils;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.common.HttpAddress;
import com.ycsj.goldmedalnewconcept.common.bean.UpdateResInfo;
import com.ycsj.goldmedalnewconcept.common.http.HttpUtils;
import com.ycsj.goldmedalnewconcept.common.util.AccountUtils;
import com.ycsj.goldmedalnewconcept.teacher.adapter.ScoreRvAdapter;
import com.ycsj.goldmedalnewconcept.teacher.bean.ClassInfo;
import com.ycsj.goldmedalnewconcept.teacher.bean.ScoreInfo;
import com.ycsj.goldmedalnewconcept.teacher.utils.ClassPoputil;
import com.ycsj.goldmedalnewconcept.teacher.utils.ClassUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 成绩管理
 * Created by Administrator on 2018/6/28 0028.
 */

public class TeacherScoreManagerActivity extends BaseActivity implements View.OnClickListener, SrfManager.OnPullRefreshListener {

    private ImageView ivBack;
    private RecyclerView rv;
    private SmartRefreshLayout srf;
    private RelativeLayout rlLoadingView;
    private RelativeLayout rlContent;
    private ImageView ivEdit;
    private ImageView ivAddTest;
    //标题栏的布局
    private LinearLayout llTitle;

    //是否获取班级列表数据完成的标识,没完成之前点击选择班级的弹框提示正在加载,不允许点击
    private boolean isLoadClassCompleted;

    //数据集合
    private List<ScoreInfo.DataBean> oldDatas;

    //空视图
    private View emptyView;

    //适配器
    private ScoreRvAdapter adapter;

    //所有班级的列表
    private List<ClassInfo.ListBean> classInfos;

    //记录弹出展示班级列表PopUpWindow的选中位置的值,默认第一个被选中
    private int popSelectedPos = 0;

    //界面刷新的标识
    public static final int REFRESHDATA = 0x330;

    //页码
    private int page = 0;

    @Override
    protected int getContentLayout() {
        return R.layout.activity_teacher_score_manager;
    }

    @Override
    protected void init() {

        //设置状态栏颜色
        StateBarUtil.customImmerseBar(this);

        //初始化视图
        initView();

        //初始化下拉刷新控件
        initSrf();

        //请求班级数据
        httpClass();

    }

    /**
     * 初始化下拉刷新
     */
    private void initSrf() {
        SrfManager.setSmartByPullListener(srf, this);
    }


    /**
     * 初始化视图
     */
    public void initView() {
        ivBack = findViewById(R.id.iv_back);
        ivBack.setOnClickListener(this);
        rv = findViewById(R.id.rv);
        srf = findViewById(R.id.srf);
        rlLoadingView = findViewById(R.id.rl_loading);
        rlLoadingView.setVisibility(View.VISIBLE);
        ivEdit = findViewById(R.id.iv_edit);
        ivEdit.setOnClickListener(this);
        rlContent = findViewById(R.id.rl_content);
        //标题栏
        llTitle = findViewById(R.id.ll_title);
        ivAddTest = findViewById(R.id.iv_add);
        ivAddTest.setOnClickListener(this);
    }


    /**
     * 请求班级里列表数据
     */
    private void httpClass() {

        ClassUtil.httpClass(rlLoadingView, this, new ClassUtil.onSuccessListener() {
            @Override
            public void onSuccess(List<ClassInfo.ListBean> datas) {
                //回调班级数据
                classInfos = datas;

                //证明有班级
                ivEdit.setVisibility(View.VISIBLE);
                ivAddTest.setVisibility(View.VISIBLE);

                //改变加载完成的标记
                isLoadClassCompleted = true;

                //设置数据
                initRv();

                //请求页面列表数据
                httpPageData(popSelectedPos, BqaManager.NORML);
            }

            @Override
            public void hasNoData() {
                //没有班级,不显示顶部的切换班级的按钮和
                ivEdit.setVisibility(View.INVISIBLE);
                ivAddTest.setVisibility(View.INVISIBLE);
            }
        });
    }

    /**
     * 请求页面数据的方法
     *
     * @param popSelectedPos
     */
    private void httpPageData(int popSelectedPos, final int method) {

        if (method == BqaManager.NORML) {
            page = 0;
        } else {
            page++;
        }

        Map<String, String> map = new HashMap<>();
        map.put("type", "18");
        map.put("acc", AccountUtils.getAccount(this));
        map.put("role", AccountUtils.getRole(this));
        map.put("apptoken", AccountUtils.getToken(this));
        map.put("userClass", classInfos.get(popSelectedPos).getNum() + "");
        map.put("platform", "2");

        HttpUtils.post(HttpAddress.SCOREMANAGE, map, this, new HttpUtils.CallBack() {

            @Override
            public void onError(Call call, Exception e, int id) {
                BqaManager.setErrorNet(rlLoadingView, srf, method, adapter);
            }

            @Override
            public void onResponse(String response, int id) {
                if (rlLoadingView != null && rlLoadingView.getVisibility() == View.VISIBLE) {
                    rlLoadingView.setVisibility(View.GONE);
                }

                if (rlContent != null && rlContent.getVisibility() != View.VISIBLE) {
                    rlContent.setVisibility(View.VISIBLE);
                }

                CustomDialogManager.dissmiss();

                if (!TextUtils.isEmpty(response)) {
                    ScoreInfo info = null;
                    try {
                        info = GsonUtil.jsonToBean(response, ScoreInfo.class);
                    } catch (Exception e) {
                        Log.i("test", "数据解析异常");
                    }

                    if (null != info && "200".equals(info.getState())) {

                        //返回成功
                        List<ScoreInfo.DataBean> newDatas = info.getData();
                        LogUtils.iTag("test", "返回的数据");
                        LogUtils.iTag("test", newDatas);
                        LogUtils.iTag("test", newDatas == null);


                        if (newDatas != null) {
                            if (method == BqaManager.NORML) {
                                oldDatas.clear();
                                oldDatas.addAll(newDatas);
                                BqaManager.setRv(emptyView, TeacherScoreManagerActivity.this, adapter, rv);
                            } else {
                                //更新数据
                                BqaManager.updateRvBySmf(method, srf, rv, oldDatas, newDatas, adapter);
                                adapter.setEnableLoadMore(false);
                            }
                        }
                    } else {
                        UiUtils.Toast("返回器返回异常,错误码是:" + info.getState(), false);
                        Log.i("test", "返回器返回异常,错误码是:" + info.getState());
                    }
                } else {
                    Log.i("test", "服务器返回数据为空");
                }
            }
        });
    }

    /**
     * 设置列表
     */
    private void initRv() {
        oldDatas = new ArrayList<>();
        emptyView = View.inflate(this, R.layout.base_rv_common_empty_view, null);
        TextView tvMsg = emptyView.findViewById(R.id.tv_content);
        tvMsg.setText("您还未上传考试成绩");
        adapter = new ScoreRvAdapter(this, R.layout.teacher_rv_score_manager, oldDatas);
    }

    /**
     * 弹出展示班级列表的方法
     */
    private void showClassPop() {
        ClassPoputil.showClassPop(this, classInfos, popSelectedPos, llTitle, new ClassPoputil.onPopItemClickListener() {
            @Override
            public void onItemClick(int pos) {

                //记录当前点击条目的位置
                popSelectedPos = pos;

                CustomDialogManager.show(TeacherScoreManagerActivity.this, "请求中...");

                //请求页面数据
                httpPageData(popSelectedPos, BqaManager.PULLREFRESH);

            }
        });
    }

    /**
     * 添加测试主题
     */
    private void addTestTagAction() {

        PopUpManager.showPop(this, R.layout.teacher_pop_updatetag, 0.3f, this, new PopUpManager.onGetViewListener() {
            @Override
            public void getChildView(View view, int layoutResId) {
                ImageView ivDelete = view.findViewById(R.id.lv_close);
                Button btCommit = view.findViewById(R.id.bt_commit);
                final EditText etMsg = view.findViewById(R.id.et_message);
                TextView tv_title = view.findViewById(R.id.tv_title);

                tv_title.setText("添加测试主题");

                ivDelete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        PopUpManager.dismiss();
                    }
                });

                btCommit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        String content = etMsg.getText().toString().trim();
                        if (TextUtils.isEmpty(content)) {
                            UiUtils.Toast("请先输入内容", false);
                            return;
                        } else {
                            //提交服务器
                            doUpdateTagAction(content);
                        }
                    }
                });
            }
        });
    }


    /**
     * 上传服务器测试主题
     */
    private void doUpdateTagAction(String tag) {
        PopUpManager.dismiss();
        CustomDialogManager.show(this, "添加中...");
        Map<String, String> map = new HashMap<>();
        map.put("type", "17");
        map.put("acc", AccountUtils.getAccount(this));
        map.put("role", AccountUtils.getRole(this));
        map.put("userClass", classInfos.get(popSelectedPos).getNum() + "");
        map.put("tag", tag);
        map.put("apptoken", AccountUtils.getToken(this));
        map.put("platform", "2");


        HttpUtils.post(HttpAddress.SCORETHEME, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                CustomDialogManager.dissmiss();
                UiUtils.Toast(BaseApplication.ERROR, false);
            }

            @Override
            public void onResponse(String response, int id) {
                CustomDialogManager.dissmiss();
                if (!TextUtils.isEmpty(response)) {
                    UpdateResInfo info = null;
                    try {
                        info = GsonUtil.jsonToBean(response, UpdateResInfo.class);
                    } catch (Exception e) {
                        Log.i("test", "数据解析异常");
                    }

                    if (null != info) {
                        if ("200".equals(info.getState())) {
                            //返回成功
                            UiUtils.Toast("添加主题成功", false);
                            //通知页面刷新
                            httpPageData(popSelectedPos, BqaManager.PULLREFRESH);
                        } else {
                            UiUtils.Toast("添加失败,返回错误码:" + info.getState(), false);
                            Log.i("test", "返回器返回异常,错误码是:" + info.getState());
                        }
                    }
                } else {
                    Log.i("test", "服务返回数据异常");
                }
            }
        });
    }


    /**
     * 下拉刷新
     *
     * @param refreshlayout
     */
    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        httpPageData(popSelectedPos, BqaManager.PULLREFRESH);
    }

    /**
     * 事件处理
     *
     * @param busInfo
     */
    @Override
    public void busEvent(BusInfo busInfo) {
        super.busEvent(busInfo);
        if (null != busInfo && busInfo.type == REFRESHDATA) {
            //刷新页面数据
            httpPageData(popSelectedPos, BqaManager.PULLREFRESH);
        }
    }

    /**
     * 点击事件
     *
     * @param view
     */
    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_back) {
            //返回
            finish();
        } else if (id == R.id.iv_edit) {
            //选择班级
            if (isLoadClassCompleted) {
                //弹出选择班级的PopUpWindow
                showClassPop();
            } else {
                //没加载完成
//                SnackbarUtil.ShortSnackbar(llBaseMain, Constants.LOADING, 0).show();
            }
        } else if (id == R.id.iv_add) {
            if (isLoadClassCompleted) {
                //添加测试主题
                addTestTagAction();
            } else {
//                SnackbarUtil.ShortSnackbar(llBaseMain, Constants.LOADING, 0).show();
            }
        }
    }
}
